package cn.com.netedge.iot.frontend.biz.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSubscriberInitializer {

    private final RedisMessageListenerContainer container;
    private final RedisMessageSubscriber messageSubscriber;
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisSubscriberInitializer(RedisMessageListenerContainer container,
                                      RedisMessageSubscriber messageSubscriber,
                                      RedisTemplate<String, String> redisTemplate) {
        this.container = container;
        this.messageSubscriber = messageSubscriber;
        this.redisTemplate = redisTemplate;

        // 初始化订阅
        addSubscriptions();

        // 启动重连检测任务
        startReconnectTask();
    }

    private void addSubscriptions() {
        container.addMessageListener(messageSubscriber, new ChannelTopic(CacheKeyConstants.KEY_DEVICE_TASK_RESULT));
        container.addMessageListener(messageSubscriber, new ChannelTopic(CacheKeyConstants.TIME_TASK_CHANNEL_NAME));
        container.addMessageListener(messageSubscriber, new ChannelTopic(CacheKeyConstants.PARA_SETUP_TASK_CHANNEL_NAME));
    }

    private void startReconnectTask() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                // 检测 Redis 连接是否有效
                redisTemplate.getConnectionFactory().getConnection().ping();
                System.out.println("Redis connection is healthy.");
            } catch (Exception e) {
                System.err.println("Redis connection lost. Re-subscribing...");
                container.stop();
                addSubscriptions();
                container.start();
            }
        }, 0, 10, TimeUnit.SECONDS); // 每隔 10 秒检测一次
    }
}
